package com.rowline.admin.module.util.interceptor;

import com.rowline.admin.module.util.context.RequestContext;
import com.rowline.admin.module.util.domain.Log;
import com.rowline.admin.module.util.utils.FastJsonUtil;
import com.rowline.admin.module.util.utils.HttpRequestUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * ClassName:LogInterceptor
 * Created by 245167
 * on 2017/8/11  11:17
 * description:日志拦截器
 */
@Component
public class LogInterceptor implements HandlerInterceptor{

    // 执行controller之前
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse,
                             Object o) throws Exception {
        String totalRequestParams = getTotalRequestParams(httpServletRequest);
        Log.info("sprinMVC LogInterceptor preHandle(。。。)");
        Log.info("请求进入参数为：" + totalRequestParams);
        return true;
    }

    // 执行controller之后
    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o,
                           ModelAndView modelAndView) throws Exception {
        Log.info("sprinMVC LogInterceptor postHandle(。。。)");
        RequestContext.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o,
                                Exception e) throws Exception {
        Log.info("sprinMVC LogInterceptor afterCompletion(。。。)");
    }

    private String getTotalRequestParams(HttpServletRequest request) {

        Map<String, String> map = HttpRequestUtil.getParamers(request);

        String ip = HttpRequestUtil.getIpAddress(request);
        request.setAttribute("RemoteAddr",ip);
        map.put("RemoteAddr", ip);

        return FastJsonUtil.toJSONString(map);
    }

}
